package com.serge.smartdacha.model;

import java.util.Map;

import android.content.res.Resources;
import com.serge.smartdacha.R;

public class CosmController extends Controller {

    private static int[] INTERVALS = new int[]{-1, 5, 10, 15, 30, 60};

    private Boolean active;

    private Integer interval;

    public CosmController() {
        super("L");
    }

    @Override
    protected void init(Map<String, String> map) {
        String period = map.get("P");
        int i;
        try {
            i = Integer.parseInt(period);
        } catch (NumberFormatException e) {
            i = -1;
        }
        setActive(i > 0);
        setInterval(i);
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public Integer getInterval() {
        return interval;
    }

    public void setInterval(Integer interval) {
        this.interval = interval;
    }

    public int getMaxProgress() {
        return INTERVALS.length - 1;
    }

    public int toInterval(int progress) {
        if(progress <= 0) {
            progress = 0;
        } else if(progress >= INTERVALS.length) {
            progress = INTERVALS.length - 1;
        }
        return INTERVALS[progress];
    }

    public String toText(Resources resources, int interval) {
        if (interval < 0) {
            return resources.getString(R.string.cosm_off);
        } else {
            return resources.getString(R.string.cosm_each_n_minutes, interval);
        }
    }

    public int toProgress(Integer interval) {
        if(interval == null || interval < 0) {
            return 0;
        } else {
            for (int i = 0 ; i < INTERVALS.length ; i++) {
                if(INTERVALS[i] >= interval) {
                    return i;
                }
            }
        }
        return INTERVALS[INTERVALS.length - 1];
    }

    public String toSmsCommand(int progress) {
        int interval = toInterval(progress);
        return interval < 0 ? OFF : String.valueOf(interval);
    }
}
